//
//  StrategyVC.m
//  NewNest
//
//  Created by hesiyao on 16/1/15.
//  Copyright © 2016年 www.lanou3g.com蓝鸥科技. All rights reserved.
//

#import "StrategyVC.h"
#import <AFNetworking.h>
#import <AFHTTPSessionManager.h>
#import "StrategyModal.h"
#import "CarouselView.h"
#import "StrategyTableviewModal.h"
#import "StrategyTableViewCell.h"
#import <UIImageView+WebCache.h>
#import "StrategyDetailPageVC.h"
#import <MJRefresh.h>
#import "StrategyMoreSortView.h"
#import "StrategyMoreSortCell.h"
@interface StrategyVC () <UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, CarouselPictureDelegate>
@property (nonatomic, retain) UITableView *tableview;
@property (nonatomic, retain) NSMutableArray *carouseDataArr;
@property (nonatomic, retain) NSMutableArray *dataArr;
@property (nonatomic, retain) NSString *idString;
@property (nonatomic, assign) NSInteger number;/**< 用来保存请求新数据动态值 */
@property (nonatomic, retain) UIButton *sortButton;
@property (nonatomic, retain) UIView *sortView;/**< 分类的小视图 */
@property (nonatomic, retain) UICollectionView *collectionview;/**< 分类的collectionview */
@property (nonatomic, assign) NSInteger sortNumber;
@end

@implementation StrategyVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.automaticallyAdjustsScrollViewInsets = NO;
    //navigation
    self.navigationItem.title = @"装修攻略";
    
    // 视图初始化
    [self createSubviews];
    //数据处理
    [self dataHandler];
    //导航栏隐藏
//    [self hidden];
    //给保存请求新数据的值赋初始值
    self.number = 10;
    //装修攻略分类的数值
    self.sortNumber = 0;
    // 下拉刷新
    [self refresh];
    
}

///数据处理
- (void)dataHandler
{
    //tableView的数据处理
    NSString *tableviewStr = [NSString stringWithFormat:@"http://api.guju.com.cn/v2/strategy/strategyList?userId=0&count=10&start=0&orderString=CATEGORY&category=%ld", self.sortNumber];
    AFHTTPSessionManager *tableviewSession = [AFHTTPSessionManager manager];
    [tableviewSession GET:tableviewStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"成功");
//        NSLog(@"%@", responseObject);
        NSMutableArray *arr = responseObject[@"strategyList"];
        self.dataArr = [StrategyTableviewModal modelHanderWithArray:arr];
        [_tableview reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"攻略解析失败");
    }];
    
    // 上方轮播图的数据处理
    NSString *urlStr = @"http://api.guju.com.cn/v2/strategy/banner";
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [session GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
    
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"%@", responseObject);
        NSMutableArray *arr = responseObject[@"banners"];
        self.carouseDataArr = [StrategyModal modelHanderWithArray:arr];
        
        //设置上方的轮播图
        NSMutableArray *carouseArr = [NSMutableArray array];
        for (NSInteger i = 0; i < _carouseDataArr.count; i++) {
            StrategyModal *m = _carouseDataArr[i];
            NSString *str = m.phoneImgUrl;
            [carouseArr addObject:str];
        }
        // 创建轮播图并把它加到tableView上面
        CarouselView *carouse = [[CarouselView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height / 4) timeInterval:1.5 imageUrlArr:carouseArr urlArr:nil];
        // 签订轮播图代理
        carouse.delegate = self;
//        carouse.backgroundColor = [UIColor redColor];
//        [self.tableview addSubview:carouse];
        _tableview.tableHeaderView = carouse;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"轮播图解析失败");
    }];
    
   // 上拉刷新结束
    [self.tableview.mj_header endRefreshing];
    
}

/// 视图初始化
- (void)createSubviews
{
    
    self.tableview = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    // 给tableView设置上方空白的部分
//    _tableview.contentInset = UIEdgeInsetsMake(self.view.frame.size.height / 4, 0, 0, 0);
    [self.view addSubview:_tableview];
    _tableview.delegate = self;
    _tableview.dataSource = self;
//    _tableview.backgroundColor = [UIColor cyanColor];
    [_tableview registerClass:[StrategyTableViewCell class] forCellReuseIdentifier:@"cell"];
    [_tableview release];
    
    // 创建右上方的按钮
    self.sortButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _sortButton.frame = CGRectMake(0, 0, 25, 25);
    [_sortButton setImage:[UIImage imageNamed:@"xiangxia@2x"] forState:UIControlStateNormal];
    [_sortButton setImage:[UIImage imageNamed:@"xiangshang@2x"] forState:UIControlStateSelected];
    // 按钮的点击方法
    [_sortButton addTarget:self action:@selector(pop) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_sortButton];
    
    // 弹出的分类视图
    self.sortView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height / 2)];
    _sortView.hidden = YES;
    _sortView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:_sortView];
    [_sortView release];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    self.collectionview = [[UICollectionView alloc] initWithFrame:_sortView.bounds collectionViewLayout:layout];
    layout.itemSize = CGSizeMake((_sortView.frame.size.width - 40) / 3, _sortView.frame.size.height / 10);
    layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    [self.sortView addSubview:_collectionview];
    [_collectionview release];
    _collectionview.delegate = self;
    _collectionview.dataSource = self;
    _collectionview.backgroundColor = [UIColor whiteColor];
    
    [_collectionview registerClass:[StrategyMoreSortCell class] forCellWithReuseIdentifier:@"cell"];
    
}


/// tableview的cell的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
}

/// 设置tableview的cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    StrategyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    // 数组保护
    if (_dataArr.count != 0) {
        
        StrategyTableviewModal *m = _dataArr[indexPath.row];
        cell.titleLabel.text = m.title;
        cell.contentLabel.text = m.content;
        cell.likeLabel.text = m.likeCount.stringValue;
        cell.likeImg.image = [UIImage imageNamed:@"huiaixin@2x"];
        cell.commentImg.image = [UIImage imageNamed:@"huicomment@2x"];
        cell.commentLabel.text = m.commentCount.stringValue;
        cell.styleLabel.text = m.categoryName;
        NSString *urlStr = [NSString stringWithFormat:@"http://gooju.cn/simages/%@_0_9-.jpg",m.covorPhotoId];
        [cell.titleImg sd_setImageWithURL:[NSURL URLWithString:urlStr]];
        return cell;
    }else {
        return cell;
    }
    
}
/// 设置tableview的cell的高度
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 190;
}
/// 点击tableview进入详情页面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    StrategyDetailPageVC *detailVC = [[StrategyDetailPageVC alloc] init];
    StrategyTableviewModal *m = _dataArr[indexPath.row];
    detailVC.idStr = m.detailId;
    [self.navigationController pushViewController:detailVC animated:YES];
}

/// 导航栏隐藏
- (void)hidden
{
    // 导航栏隐藏设置
    if ([self respondsToSelector:@selector(automaticallyAdjustsScrollViewInsets)]) {
        // 取消ScrollView的内容自动调整
        self.automaticallyAdjustsScrollViewInsets = NO;
        //tableView边界预留
        UIEdgeInsets insets = self.tableview.contentInset;
        // 让上边界的预留值和导航栏相等
        insets.top = self.navigationController.navigationBar.bounds.size.height;
        //把修改后的边界预留值赋给tableView
        self.tableview.contentInset = insets;
        // 滚动指标点到滚到视图的边缘的距离
        self.tableview.scrollIndicatorInsets = insets;
    }
}

// 导航栏滚动
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    if (velocity.y > 0) {
        self.navigationController.navigationBar.hidden = YES;
        self.tabBarController.tabBar.hidden = YES;
        self.sortView.hidden = YES;
        self.sortButton.selected = NO;
    }else{
        self.navigationController.navigationBar.hidden = NO;
        self.tabBarController.tabBar.hidden = NO;
        
    }
}

// 下拉刷新 上拉加载
- (void)refresh
{
    //上拉刷新
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(dataHandler)];
    [self.tableview.mj_header beginRefreshing];
    
    //上拉加载
    self.tableview.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    //如果数据字典不为空 那么就刷新请求新的数据
    if (_dataArr.count != 0) {
        [self.tableview.mj_footer beginRefreshing];
    }
}

/// 上拉加载调用的方法
- (void)loadNewData
{
    NSString *urlStr = [NSString stringWithFormat:@"http://api.guju.com.cn/v2/strategy/strategyList?userId=0&count=10&start=%ld&orderString=CATEGORY&category=0",self.number];
    [[AFHTTPSessionManager manager] GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"攻略加载成功");
        // 创建新数组用以接收新的数据
        NSArray *newDataArr = [NSArray array];
        newDataArr = [StrategyTableviewModal modelHanderWithArray:responseObject[@"strategyList"]];
        //将新的数据依次加入保存数据的数组里面
        for (NSInteger i = 0; i < 10; i++) {
            [_dataArr addObject:newDataArr[i]];
        }
        // 刷新tableView
        [self.tableview reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"攻略加载失败");
    }];
    
    //结束刷新
    [self.tableview.mj_footer endRefreshing];
    //动态数值加10
    self.number += 10;
}

// 更多分类的按钮
- (void)pop
{
    _sortButton.selected = !_sortButton.selected;
    if (_sortButton.selected == YES) {
        _sortView.hidden = NO;
    }else {
        _sortView.hidden = YES;
    }
}

//collectionView的cell个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 21;
}

//collectionView的cell的设置
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    StrategyMoreSortCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    //    cell.backgroundColor = [UIColor cyanColor];
    if (indexPath.row == 0) {
        cell.titleLabel.text = @"装修选材";
    }else if (indexPath.row == 1) {
        cell.titleLabel.text = @"验房须知";
    }else if (indexPath.row == 2) {
        cell.titleLabel.text = @"装修合同";
    }else if (indexPath.row == 3) {
        cell.titleLabel.text = @"装修预算";
    }else if (indexPath.row == 4) {
        cell.titleLabel.text = @"装修风水";
    }else if (indexPath.row == 5) {
        cell.titleLabel.text = @"装修设计";
    }else if (indexPath.row == 6) {
        cell.titleLabel.text = @"装修要点";
    }else if (indexPath.row == 7) {
        cell.titleLabel.text = @"装修选材";
    }else if (indexPath.row == 8) {
        cell.titleLabel.text = @"建材安装";
    }else if (indexPath.row == 9) {
        cell.titleLabel.text = @"拆改工程";
    }else if (indexPath.row == 10) {
        cell.titleLabel.text = @"水电工程";
    }else if (indexPath.row == 11) {
        cell.titleLabel.text = @"防水工程";
    }else if (indexPath.row == 12) {
        cell.titleLabel.text = @"泥瓦工程";
    }else if (indexPath.row == 13) {
        cell.titleLabel.text = @"水木工程";
    }else if (indexPath.row == 14) {
        cell.titleLabel.text = @"油漆工程";
    }else if (indexPath.row == 15) {
        cell.titleLabel.text = @"装修污染";
    }else if (indexPath.row == 16) {
        cell.titleLabel.text = @"装修验收";
    }else if (indexPath.row == 17) {
        cell.titleLabel.text = @"家居护理";
    }else if (indexPath.row == 18) {
        cell.titleLabel.text = @"家居配饰";
    }else if (indexPath.row == 19){
        cell.titleLabel.text = @"家电家私";
    }else {
        cell.titleLabel.text = @"取消筛选";
    }
    return cell;
}

//点击collectionview改变分类
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        self.sortNumber = 20;
        [self dataHandler];
    }else if (indexPath.row == 1) {
        self.sortNumber = 19;
        [self dataHandler];
    }else if (indexPath.row == 2) {
        self.sortNumber = 18;
        [self dataHandler];
    }else if (indexPath.row == 3) {
        self.sortNumber = 17;
        [self dataHandler];
    }else if (indexPath.row == 4) {
        self.sortNumber = 16;
        [self dataHandler];
    }else if (indexPath.row == 5) {
        self.sortNumber = 15;
        [self dataHandler];
    }else if (indexPath.row == 6) {
        self.sortNumber = 14;
        [self dataHandler];
    }else if (indexPath.row == 7) {
        self.sortNumber = 13;
        [self dataHandler];
    }else if (indexPath.row == 8) {
        self.sortNumber = 12;
        [self dataHandler];
    }else if (indexPath.row == 9) {
        self.sortNumber = 11;
        [self dataHandler];
    }else if (indexPath.row == 10) {
        self.sortNumber = 10;
        [self dataHandler];
    }else if (indexPath.row == 11) {
        self.sortNumber = 9;
        [self dataHandler];
    }else if (indexPath.row == 12) {
        self.sortNumber = 8;
        [self dataHandler];
    }else if (indexPath.row == 13) {
        self.sortNumber = 7;
        [self dataHandler];
    }else if (indexPath.row == 14) {
        self.sortNumber = 6;
        [self dataHandler];
    }else if (indexPath.row == 15) {
        self.sortNumber = 5;
        [self dataHandler];
    }else if (indexPath.row == 16) {
        self.sortNumber = 4;
        [self dataHandler];
    }else if (indexPath.row == 17) {
        self.sortNumber = 3;
        [self dataHandler];
    }else if (indexPath.row == 18) {
        self.sortNumber = 2;
        [self dataHandler];
    }else if (indexPath.row == 19) {
        self.sortNumber = 1;
        [self dataHandler];
    }else  {
        self.sortNumber = 0;
        [self dataHandler];
    }
    
    // 收起视图 改变按钮状态
    self.sortButton.selected = NO;
    self.sortView.hidden = YES;
}

// 实现轮播图的方法
- (void)pushWithUrl:(NSString *)url
{
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
